import Component from "../Component.js";
import Type from "../../experience/db/Type.js";

const Draw = ol.interaction.Draw;
const VectorSource = ol.source.Vector;

export default class Water extends Component {
    constructor() { super()
        this.emitter.on("water-sensor-move", () => {
            const config = this.algo.getConfig();
            if (config === null) {
                this.toast('请优先选择煤矿。');
                return;
            }
            this.create();
        });
     }

    create() {
        this.toast('请添加一个面要素,双击结束操作;点击Esc取消操作,点击Del回退。');
        const source = new VectorSource(), self = this;
        const draw = new Draw({ source: source, type: 'Polygon'});
        window.onkeydown = function(event) {
            if (event.defaultPrevented) return;

            let handled = false;
            if (event.key === "Delete") {
                handled = true;
                draw.removeLastPoint();
            }

            if (event.key === "Escape") {
                handled = true;
                self.drawer.removeInteraction(draw);
                window.onkeydown = null;
            }

            if (handled) event.preventDefault();
        }

        draw.on('drawend', async (event) => {
            this.drawer.locked = true
            const config = this.algo.getConfig();
            const area = event.feature.getGeometry().flatCoordinates, coors = [];
            for (let i = 0; i < area.length - 1; i = i + 2) {
                const x = this.algo.denormalX(area[i]);
                const y = this.algo.denormalY(area[i+1]);
                coors.push([x, y]);
            }

            this.app.dialog.prompt('请输入富水区域名称.', async (name) => {
                if (name === null || name === "") {
                    this.toast("富水区域名称不能为空。");
                    return;
                }

                const water = {
                    geoType: 'POLYGON',
                    geoValue: this.utils.xys2str(coors),
                    mineCode: config.mine_code,
                    name: name,
                    description: ""
                };

                const data = await this.api.insertWater(water);
                this.toast(data.msg)
                await this.refresh();
                const json = { id: data.data, from: "tank", type: "refreshWater" };
                window.parent.postMessage(JSON.stringify(json), '*');
                this.drawer.removeInteraction(draw);
                this.drawer.locked = false
            },() => {
                this.drawer.removeInteraction(draw);
                this.drawer.locked = false
            });
        });
        this.drawer.addInteraction(draw);
    }

    async select(feature) {
        const self = this;
        self.drawer.locked = true;
        const config = this.algo.getConfig(), coors = [];
        const coordinates = feature.getGeometry().flatCoordinates;
        for (let i = 0; i < coordinates.length - 1; i = i + 2) {
            const x = this.algo.denormalX(coordinates[i]);
            const y = this.algo.denormalY(coordinates[i + 1]);
            coors.push([x, y]);
        }

        self.app.dialog.prompt('请输入富水区域名称.', async (name) => {
            if (name === null || name === "") {
                self.toast("富水区域名称不能为空。");
                return;
            }
            const data = await this.api.insertWater({
                geoType: 'POLYGON',
                geoValue: this.utils.xys2str(coors),
                mineCode: config.mine_code,
                name: name,
                description: ""
            });
            self.toast(data.msg)

            const data2 = await this.api.getWaters({ mineCode: config.mine_code });
            if (data2.data === null) {
                console.log("富水区域数据获取异常。");
                return;
            }

            await self.db.refresh(Type.Water, data2.data);
            await self.drawer.draw(Type.Water);
            const json = { id: data.data, from: "tank", type: "refreshWater" };
            window.parent.postMessage(JSON.stringify(json), '*');
            self.drawer.locked = false
        }, () => {
            self.drawer.locked = false
        });
    }

    async refresh() {
        const config = this.algo.getConfig();
        if (config == null) {
            console.log("配置文件获取异常。");
            return;
        }

        const data = await this.api.getWaters({ mineCode: config.mine_code });
        if (data.data === null) {
            console.log("富水区域数据获取异常。");
            return;
        }

        await this.db.refresh(Type.Water, data.data);
        await this.drawer.draw(Type.Water);
    }

    template() { }

    control() {
        // 从选择器接收发来的消息
        this.emitter.on("water-deleted", async () => {
            this.emitter.locked = true;

            const id = this.emitter.params[0], self = this;
            const dialog = self.app.dialog.confirm('确认将服务器的数据删除?', async () => {
                const config = self.algo.getConfig();
                const data = await self.api.deleteWater({
                    id: id, mineCode: config.mine_code
                });
                self.toast(data.msg);

                const data2 = await this.api.getWaters({
                    mineCode: config.mine_code
                });
                if (data2.data === null) {
                    console.log("富水区域数据获取异常。");
                    return;
                }

                await self.db.refresh(Type.Water, data2.data);
                await self.drawer.draw(Type.Water);
                const json = { id: data.data, from: "tank", type: "refreshWater" };
                window.parent.postMessage(JSON.stringify(json), '*');

                this.emitter.emit("cancel-selected");
                this.emitter.locked = false;
            }, () => {
                this.emitter.emit("cancel-selected");
                this.emitter.locked = false;
                dialog.close();
            });
        });

        this.$$("#drawing-water").on("click", () => {
            const config = this.algo.getConfig();
            if (config === null) {
                this.toast('请优先选择煤矿。');
                return;
            }
            this.create();
        });
    }
}